<?php

include_once("../../php/db/config.php");

class MySQLiWrapper {
	var $dbhost = HOSTNAME;
	var $dbname = DATABASE;
	var $dbuser = USERNAME;
	var $dbpass = PASSWORD;
	var $mysqli;
	var $result;		// to be used for Single Queries (simple array result)
	var $results;		// to be used for Multi Queries (associative array with arrays)

	function MySQLiWrapper()
	    {
	    // Instantiate object
	    $this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
	    // Call the init method to allow setting of options
	    //$this->mysqli->init();

	    // set relevant options
	    //$this->mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
	    //$this->mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
	    }	
	public function connect()
	    {
	    // connect
	    $this->mysqli->real_connect($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
	    if (mysqli_connect_errno()) 
		{
   		printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
   		exit;
		}
	    }
	public function disconnect()
	    {
	    //if ($this->result)
	    //	$this->result->close();
	    // Destroy connection handler object
	    if ($this->mysqli)
	        $this->mysqli->close();
	    }

	/* Send a query to the server and return result */ 
	public function Query($query)
	    {
	    if($res = $this->mysqli->real_query($query))
		{
	        // clean existing results store
	        $this->result = array();

	    	if ($result = $this->mysqli->store_result())
		    {
		    $this->result[0] = $result->fetch_array();
		    $result->close();
	            return $this->result;
		    }
		}
	    return ($this->mysqli->errno) ? $this->mysqli->error : "unknown error";
	    }
	/* same same but with Multi Query */
	public function MQuery($query)
	    {
	    // clean existing results store
	    $this->results = array();

	    if ($this->mysqli->multi_query($query))
		{
		$counter = 0;
		// loop over results
		do
		    {
	            if ($result = $this->mysqli->store_result())
			{
			while ($row = $result->fetch_assoc())
			    $this->results[$counter++] = $row;
			$result->close();
			}
		    }
		while ($this->mysqli->next_result());
		}
	    else 
		{
		return ($this->mysqli->errno) ? $this->mysqli->error : "unknown error";
		}

	    return $this->results;
	    }

}

?>
